<template>
  <div class="app-container">
    <bpmn-modeler
      :xml="xml"
      :users="users"
      :groups="groups"
      :postList="postList"
      :categorys="categorys"
      :exps="exps"
      :nodeText="nodeText"
      :enable="enable"
      @save="save"
      @show-x-m-l="showXML"
      @start-up="startUp"
      @handle-node="handleNode"
      @fallback="fallback"
    />
    <el-drawer :title="xmlTitle" :modal="false" direction="rtl" v-model="xmlOpen" size="60%">
      <el-scrollbar>
        <pre>
          {{ xmlData }}
        </pre>
      </el-scrollbar>
    </el-drawer>
    <el-dialog v-model="visible" title="查看流程图版本" width="600px">
      <el-table :data="flowList" @row-click="checkFlowChart" tooltip-effect>
        <el-table-column label="编码" prop="code" show-overflow-tooltip />
        <el-table-column label="版本号" prop="version" />
        <el-table-column label="是否启用" prop="enable">
          <template #default="{ row }">
            <span>{{ row.enable ? '是' : '否' }}</span>
          </template>
        </el-table-column>
        <el-table-column>
          <template #default="{ row }">
            <el-button v-if="!row.enable" link type="primary" @click.stop="tableStartUp(row)"
              >启用流程
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getFlowChartList"
      />
    </el-dialog>
  </div>
</template>

<script setup>
  import { ref } from 'vue';
  import { useRoute } from 'vue-router';
  import { WorkflowBpmnModeler as bpmnModeler } from '@/components/Process/index';
  import vkBeautify from 'vkbeautify';
  import modal from '@/plugins/modal';
  import { getDicts } from '@/api/system/dict/data';
  import { listUser } from '@/api/system/user';
  import { listRole } from '@/api/system/role';
  import { listPost } from '@/api/system/post';
  import {
    flowChart,
    flowChartDetail,
    flowChartList,
    openFlowChart,
    savFlowChart,
  } from '@/api/flowable/process-list';
  import { ElMessageBox } from 'element-plus';

  const route = useRoute();

  const xml = ref(''); // 后端查询到的xml
  const modeler = ref(null);
  const xmlOpen = ref(false);
  const xmlTitle = ref('');
  const xmlData = ref(getXmlData(''));
  const users = ref([]);
  const groups = ref([]);
  const postList = ref([]);
  const categorys = ref([]);
  const exps = ref([]);
  const nodeText = ref('');
  const flowList = ref([]);
  const visible = ref(false);
  const enable = ref(false);
  const total = ref(0);
  const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
  });
  const currentFlowChartId = ref(null);

  function getXmlData(deployId) {
    if (!deployId) return;
    flowChart(deployId).then((res) => {
      nodeText.value = res.data.code;
      enable.value = res.data.enable;
      xml.value = res.data.content;
      modeler.value = res.data;
    });
  }

  function save(data) {
    const params = {
      designId: route.query.id,
      name: data.process.name,
      category: data.process.category,
      content: data.xml,
      remark: data.process.documentation,
    };
    savFlowChart(params).then((res) => {
      modal.msgSuccess(res.msg);
      getFlowChartDetail(res.data);
      getFlowChartList();
      // 关闭当前标签页并返回上个页面
      // history.back(-1);
    });
  }

  function getDataList() {
    listUser({}, { pageNum: 1, pageSize: 100 }).then((res) => {
      const data = res?.data?.records ?? [];
      data.forEach((val) => {
        val.userId = val.userId.toString();
      });
      users.value = data;
    });
    listRole({}, { pageNum: 1, pageSize: 100 }).then((res) => {
      const data = res?.data?.records ?? [];
      data.forEach((val) => {
        val.roleId = val.roleId.toString();
      });
      groups.value = data;
    });
    listPost({}, { pageNum: 1, pageSize: 100 }).then((res) => {
      const data = res?.data?.records ?? [];
      data.forEach((val) => {
        val.postId = val.postId.toString();
      });
      postList.value = data;
    });
    // 表达式
    // expList().then((res) => {
    //   exps.value = res.data;
    // });
  }

  function showXML(data) {
    xmlTitle.value = 'xml查看';
    xmlOpen.value = true;
    xmlData.value = vkBeautify.xml(data);
  }

  function fallback() {
    history.back();
  }

  function getFlowChartDetail(id) {
    currentFlowChartId.value = id;
    flowChartDetail(id).then((res) => {
      nodeText.value = res.data.code;
      enable.value = res.data.enable;
      xml.value = res.data.content;
      modeler.value = res.data;
      visible.value = false;
    });
  }

  // 获取流程图列表数据
  function getFlowChartList() {
    flowChartList(route.query.id, queryParams.value).then((res) => {
      flowList.value = res?.data?.records ?? [];
      total.value = res?.data?.total ?? 0;
    });
  }

  // 启用流程
  function startUp(row) {
    ElMessageBox.confirm('启用后，新提交的数据将按此版本的流程流转。', '确定要启用流程吗？', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        if (xml.value === row.xml) {
          openFlowChart(row?.id || currentFlowChartId.value).then(() => {
            modal.msgSuccess('操作成功');
            getFlowChartList();
            enable.value = true;
          });
        } else {
          const params = {
            designId: route.query.id,
            name: row.process.name,
            category: row.process.category,
            content: row.xml,
            remark: row.process.documentation,
          };
          savFlowChart(params).then((res) => {
            openFlowChart(res.data).then(() => {
              modal.msgSuccess('操作成功');
              getFlowChartDetail(res.data);
              getFlowChartList();
              enable.value = true;
            });
          });
        }
      })
      .catch(() => {});
  }

  // 列表启用流程
  function tableStartUp(row) {
    ElMessageBox.confirm('启用后，新提交的数据将按此版本的流程流转。', '确定要启用流程吗？', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      openFlowChart(row?.id || currentFlowChartId.value).then(() => {
        modal.msgSuccess('操作成功');
        getFlowChartList();
        checkFlowChart(row || { id: currentFlowChartId.value });
        enable.value = true;
      });
    });
  }

  function handleNode() {
    visible.value = true;
  }

  function checkFlowChart(row) {
    getFlowChartDetail(row.id);
  }

  function init() {
    const deployId = route.query && route.query.id;
    //  查询流程xml
    if (deployId) {
      getXmlData(deployId);
    }
    getDicts('sys_process_category').then((res) => {
      categorys.value = res.data;
    });
    getDataList();
    getFlowChartList();
  }

  init();
</script>

<style lang="scss" scoped></style>
